package com.xm.zcf.action.user;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.xm.zcf.domain.adminuser.Adminuser;
import com.xm.zcf.service.user.UserService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

/**
 * Created by Administrator on 2017/3/29.
 */
@Controller
@Scope("prototype")
public class UserAction extends ActionSupport implements ModelDriven<Adminuser>{
    private Adminuser model=new Adminuser();
    private String validatecode;

    public String getValidatecode() {
        return validatecode;
    }

    public void setValidatecode(String validatecode) {
        this.validatecode = validatecode;
    }

    public void validateRegist() {
        if(model.getUsername()==null||"".equals(model.getUsername())){
            this.addFieldError("username","用户名不能为空");
        }if(model.getPassword()==null||"".equals(model.getPassword())){
            this.addFieldError("password","密码不能为空");
        }
    }

    @Resource
    private UserService userService;
    public String registUI(){
        return "registUI";
    }
    public String regist(){
        String trueCode=(String) ActionContext.getContext().getSession().get("code");
        if(trueCode.equalsIgnoreCase(validatecode)){
            userService.save(model);
            return "registSuccess";
        }else{
            this.addFieldError(
                    "registcodefail","验证码不正确");
            return "registFail";
        }
    }
    public String loginUI(){return "loginUI";}
    public String login(){
        String trueCode=(String) ActionContext.getContext().getSession().get("code");
        if(!trueCode.equalsIgnoreCase(validatecode)){
            this.addFieldError("logincodefail","验证码不正确");
            return "loginFail";
        }
        Adminuser existUser=userService.findByUser(model.getUsername(),model.getPassword());
        if(existUser==null){
            this.addFieldError("loginFail","用户名或者密码错误");
            return "loginFail";
        }else {
            ActionContext.getContext().getSession().put("existUser",existUser);
            return "loginSuccess";
        }
    }
    public String loginOut(){
        ActionContext.getContext().getSession().put("existUser",null);
        return "loginSuccess";
    }
    public String registPage(){
        return "registPage";
    }
    public String loginPage(){
        return "loginPage";
    }
    @Override
    public Adminuser getModel() {
        return model;
    }
}
